package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dto.WarehousingEntryDTO;
import com.itheima.dto.WarehousingEntryDetailsDTO;
import com.itheima.mapper.*;
import com.itheima.pojo.*;
import com.itheima.qo.ItemSpuQuery;
import com.itheima.qo.PageQuery;
import com.itheima.service.WarehousingEntryService;
import com.itheima.vo.PageResult;
import com.itheima.vo.Result;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/stockAsn")
public class StockAsnController {

    @Autowired
    private WarehousingEntryService warehousingEntryService;

    @Autowired
    private WarehousingEntryDetailsMapper warehousingEntryDetailsMapper;

    @Autowired
    private WarehousingEntryDetailsSortMapper warehousingEntryDetailsSortMapper;

    @Autowired
    private WarehousingEntryUpMapper warehousingEntryUpMapper;

    @Autowired
    private ItemSpuMapper itemSpuMapper;

    @Autowired
    private ItemSkuMapper itemSkuMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private ConsignorMapper consignorMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WarehouseAreaLocaMapper warehouseAreaLocaMapper;


    // ==================== 到货通知接口 ====================

    /**
     * 分页查询到货通知列表
     *
     * @param current      当前页码
     * @param size         每页条数
     * @param supplierName 供应商名称（模糊查询）
     * @param skuCode      规格编码（模糊查询）
     * @return 分页数据
     */
    @GetMapping("/arrivalNotification/page")
    public Result queryArrivalNotificationPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String skuCode) {
        // 实现分页查询逻辑
        Page<WarehousingEntry> page = new Page<>(current, size);

        // 构造查询条件
        LambdaQueryWrapper<WarehousingEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarehousingEntry::getIsDel, 1); // 未删除的记录

        // 执行分页查询
        Page<WarehousingEntry> resultPage = warehousingEntryService.page(page, queryWrapper);

        PageResult pageResult = new PageResult();
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setData(resultPage.getRecords());
        pageResult.setPages((int) resultPage.getPages());
        pageResult.setCurrentPage(current);
        Result result = Result.success();
        result.setData(pageResult);
        return result;
    }

    /**
     * 根据ID查询到货通知详情
     *
     * @param id 到货通知ID
     * @return 到货通知详情
     */
    @GetMapping("/arrivalNotification/{id}")
    public Result queryArrivalNotificationById(@PathVariable Long id) {
        // 查询入库单主表信息
        WarehousingEntry entry = warehousingEntryService.getById(id);
        if (entry == null) {
            return Result.error("未找到对应的到货通知");
        }

        // 构造返回的DTO对象
        WarehousingEntryDTO dto = new WarehousingEntryDTO();
        dto.setId(entry.getId());
        dto.setOwnerId(entry.getConsignorId());
        dto.setOwnerName(getConsignorNameById(entry.getConsignorId())); // 根据货主ID查询货主名称
        dto.setBatch(entry.getBatchNumber());
        dto.setExpectedArrivalTime(entry.getPredictedArrivalTime());

        // 查询明细信息
        LambdaQueryWrapper<WarehousingEntryDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarehousingEntryDetails::getWarehousingEntryId, id);
        queryWrapper.eq(WarehousingEntryDetails::getIsDel, 1);
        List<WarehousingEntryDetails> detailsList = warehousingEntryDetailsMapper.selectList(queryWrapper);

        // 转换明细为DTO
        List<WarehousingEntryDetailsDTO> items = new ArrayList<>();
        for (WarehousingEntryDetails detail : detailsList) {
            WarehousingEntryDetailsDTO item = new WarehousingEntryDetailsDTO();
            item.setId(detail.getId());

            // 设置默认值
            item.setPrice(detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);

            // 根据skuId查询商品信息
            if (detail.getSkuId() != null && detail.getSkuId() > 0) {
                try {
                    ItemSku sku = itemSkuMapper.getById(detail.getSkuId());
                    if (sku != null) {
                        item.setSkuCode(sku.getCode() != null ? sku.getCode() : "");
                        item.setGoodsName(sku.getTitle() != null ? sku.getTitle() : "");

                        // 根据spuId查询SPU信息获取商品编码和供应商
                        ItemSpu spu = itemSpuMapper.getById(sku.getSpuId());
                        if (spu != null) {
                            item.setGoodsCode(spu.getId() != null ? spu.getId().toString() : "");
                            item.setSupplierName(spu.getSupplierName() != null ? spu.getSupplierName() : "");
                        }
                    }
                } catch (Exception e) {
                    // 发生异常时保持默认值
                }
            }

            items.add(item);
        }

        dto.setItems(items);

        return Result.success(dto);
    }

    /**
     * 根据货主ID获取货主名称
     * @param consignorId 货主ID
     * @return 货主名称
     */
    private String getConsignorNameById(Long consignorId) {
        if (consignorId != null) {
            Consignor consignor = consignorMapper.selectById(consignorId);
            if (consignor != null) {
                return consignor.getConsignorName();
            }
        }
        return "";
    }
    /**
     * 新增到货通知
     *
     * @param warehousingEntryDTO 到货通知数据
     * @return 操作结果
     */
    @PostMapping("/arrivalNotification")
    public Result addArrivalNotification(@RequestBody WarehousingEntryDTO warehousingEntryDTO) {
        warehousingEntryService.addArrivalNotification(warehousingEntryDTO);
        return Result.success();
    }

    /**
     * 修改到货通知
     *
     * @param warehousingEntryDTO 到货通知数据
     * @return 操作结果
     */
    @PutMapping("/arrivalNotification")
    public Result updateArrivalNotification(@RequestBody WarehousingEntryDTO warehousingEntryDTO) {
        warehousingEntryService.updateArrivalNotification(warehousingEntryDTO);
        return Result.success();
    }

    /**
     * 删除到货通知
     *
     * @param id 到货通知ID
     * @return 操作结果
     */
    @DeleteMapping("/arrivalNotification/{id}")
    public Result deleteArrivalNotification(@PathVariable Long id) {
        warehousingEntryService.deleteArrivalNotification(id);
        return Result.success();
    }

    // ==================== 待到货接口 ====================

    /**
     * 分页查询待到货列表
     *
     * @param current      当前页码
     * @param size         每页条数
     * @param supplierName 供应商名称（模糊查询）
     * @param skuCode      规格编码（模糊查询）
     * @return 分页数据
     */
    @GetMapping("/waitingForArrival/page")
    public Result queryWaitingForArrivalPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String skuCode) {
        // 实现分页查询逻辑
        Page<WarehousingEntryDetails> page = new Page<>(current, size);

        // 构造查询条件
        LambdaQueryWrapper<WarehousingEntryDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarehousingEntryDetails::getIsDel, 1); // 未删除的记录
        queryWrapper.eq(WarehousingEntryDetails::getStatus, 1); // 状态为未到货

        // 执行分页查询
        Page<WarehousingEntryDetails> resultPage = warehousingEntryDetailsMapper.selectPage(page, queryWrapper);

        // 转换数据格式以匹配前端需要的字段
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (WarehousingEntryDetails detail : resultPage.getRecords()) {
            Map<String, Object> record = new HashMap<>();
            record.put("id", detail.getId());

            // 根据skuId查询商品信息
            if (detail.getSkuId() != null && detail.getSkuId() > 0) {
                try {
                    ItemSku sku = itemSkuMapper.getById(detail.getSkuId());
                    if (sku != null) {
                        record.put("goodsCode", sku.getCode() != null ? sku.getCode() : "");
                        record.put("goodsName", sku.getTitle() != null ? sku.getTitle() : "");
                        record.put("skuCode", sku.getCode() != null ? sku.getCode() : "");
                        record.put("skuName", sku.getTitle() != null ? sku.getTitle() : "");
                        record.put("price", sku.getPrice() != null ? sku.getPrice().doubleValue() :
                                (detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0));

                        // 计算总重量和总体积
                        int count = detail.getCount() != null ? detail.getCount() : 0;
                        if (sku.getProductWeight() != null) {
                            record.put("totalWeight", sku.getProductWeight().doubleValue() * count / 1000); // 转换为kg
                        } else {
                            record.put("totalWeight", 0.0);
                        }

                        if (sku.getProductVolume() != null) {
                            record.put("totalVolume", sku.getProductVolume().doubleValue() * count / 1000000); // 转换为立方米
                        } else {
                            record.put("totalVolume", 0.0);
                        }

                        // 根据spuId查询SPU信息获取供应商
                        ItemSpu spu = itemSpuMapper.getById(sku.getSpuId());
                        if (spu != null) {
                            record.put("supplierId", spu.getSupplierId() != null ? spu.getSupplierId() : "");
                            record.put("supplierName", supplierMapper.getById(Math.toIntExact(spu.getSupplierId())).getSupplierName() != null ?
                                    supplierMapper.getById(Math.toIntExact(spu.getSupplierId())).getSupplierName() : "");
                        } else {
                            // 如果SPU查询不到，则尝试通过detail中的supplierId查询
                            if (detail.getSupplierId() != null && detail.getSupplierId() > 0) {
                                Supplier supplier = supplierMapper.getById(Math.toIntExact(detail.getSupplierId()));
                                if (supplier != null) {
                                    record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                                } else {
                                    record.put("supplierName", "");
                                }
                            } else {
                                record.put("supplierName", "");
                            }
                        }
                    } else {
                        // SKU未找到时使用默认值
                        record.put("goodsCode", "");
                        record.put("goodsName", "");
                        record.put("skuCode", "");
                        record.put("skuName", "");
                        record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                        record.put("totalWeight", 0.0);
                        record.put("totalVolume", 0.0);

                        // 通过detail中的supplierId查询供应商名称
                        if (detail.getSupplierId() != null && detail.getSupplierId() > 0) {
                            Supplier supplier = supplierMapper.getById(Math.toIntExact(detail.getSupplierId()));
                            if (supplier != null) {
                                record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                            } else {
                                record.put("supplierName", "");
                            }
                        } else {
                            record.put("supplierName", "");
                        }
                    }
                } catch (Exception e) {
                    // 异常时使用默认值
                    record.put("goodsCode", "");
                    record.put("goodsName", "");
                    record.put("skuCode", "");
                    record.put("skuName", "");
                    record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                    record.put("totalWeight", 0.0);
                    record.put("totalVolume", 0.0);

                    // 通过detail中的supplierId查询供应商名称
                    if (detail.getSupplierId() != null && detail.getSupplierId() > 0) {
                        Supplier supplier = supplierMapper.getById(Math.toIntExact(detail.getSupplierId()));
                        if (supplier != null) {
                            record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                        } else {
                            record.put("supplierName", "");
                        }
                    } else {
                        record.put("supplierName", "");
                    }
                }
            } else {
                // 没有SKU ID时使用默认值
                record.put("goodsCode", "");
                record.put("goodsName", "");
                record.put("skuCode", "");
                record.put("skuName", "");
                record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                record.put("totalWeight", 0.0);
                record.put("totalVolume", 0.0);

                // 通过detail中的supplierId查询供应商名称
                if (detail.getSupplierId() != null && detail.getSupplierId() > 0) {
                    Supplier supplier = supplierMapper.getById(Math.toIntExact(detail.getSupplierId()));
                    if (supplier != null) {
                        record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                    } else {
                        record.put("supplierName", "");
                    }
                } else {
                    record.put("supplierName", "");
                }
            }

            // 查询货主信息
            WarehousingEntry entry = warehousingEntryService.getById(detail.getWarehousingEntryId());
            if (entry != null) {
                String ownerName = getConsignorNameById(entry.getConsignorId());
                record.put("ownerName", ownerName != null ? ownerName : "");
            } else {
                record.put("ownerName", "");
            }

            dataList.add(record);
        }

        PageResult pageResult = new PageResult();
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setData(dataList);
        pageResult.setPages((int) resultPage.getPages());
        pageResult.setCurrentPage(current);
        Result result = Result.success();
        result.setData(pageResult);
        return result;
    }

    /**
     * 确认到货
     *
     * @param data 确认参数
     * @return 操作结果
     */
    @PostMapping("/waitingForArrival/confirm")
    public Result confirmArrival(@RequestBody ConfirmArrivalRequest data) {
        try {
            warehousingEntryService.confirmArrival(data.getIds(), data.getArrivalTime());
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    // ==================== 待卸货接口 ====================

    /**
     * 分页查询待卸货列表
     *
     * @param current      当前页码
     * @param size         每页条数
     * @param supplierName 供应商名称（模糊查询）
     * @param skuCode      规格编码（模糊查询）
     * @return 分页数据
     */
    @GetMapping("/toBeUnloaded/page")
    public Result queryToBeUnloadedPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String skuCode) {
        // 实现分页查询逻辑
        Page<WarehousingEntryDetails> page = new Page<>(current, size);

        // 构造查询条件
        LambdaQueryWrapper<WarehousingEntryDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarehousingEntryDetails::getIsDel, 1); // 未删除的记录
        queryWrapper.eq(WarehousingEntryDetails::getStatus, 2); // 状态为已到货

        // 执行分页查询
        Page<WarehousingEntryDetails> resultPage = warehousingEntryDetailsMapper.selectPage(page, queryWrapper);

        // 转换数据格式以匹配前端需要的字段
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (WarehousingEntryDetails detail : resultPage.getRecords()) {
            Map<String, Object> record = new HashMap<>();
            record.put("id", detail.getId());

            // 根据skuId查询商品信息
            if (detail.getSkuId() != null && detail.getSkuId() > 0) {
                try {
                    ItemSku sku = itemSkuMapper.getById(detail.getSkuId());
                    if (sku != null) {
                        record.put("goodsCode", sku.getCode() != null ? sku.getCode() : "");
                        record.put("goodsName", sku.getTitle() != null ? sku.getTitle() : "");
                        record.put("skuCode", sku.getCode() != null ? sku.getCode() : "");
                        record.put("skuName", sku.getTitle() != null ? sku.getTitle() : "");
                        record.put("price", sku.getPrice() != null ? sku.getPrice().doubleValue() :
                                (detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0));

                        // 计算总重量和总体积
                        int count = detail.getCount() != null ? detail.getCount() : 0;
                        if (sku.getProductWeight() != null) {
                            record.put("totalWeight", sku.getProductWeight().doubleValue() * count / 1000); // 转换为kg
                        } else {
                            record.put("totalWeight", 0.0);
                        }

                        if (sku.getProductVolume() != null) {
                            record.put("totalVolume", sku.getProductVolume().doubleValue() * count / 1000000); // 转换为立方米
                        } else {
                            record.put("totalVolume", 0.0);
                        }

                        // 根据spuId查询SPU信息获取供应商和货主
                        ItemSpu spu = itemSpuMapper.getById(sku.getSpuId());
                        if (spu != null) {
                            record.put("supplierId", spu.getSupplierId());
                            record.put("supplierName", supplierMapper.getById(spu.getSupplierId()).getSupplierName()!= null ?supplierMapper.getById(spu.getSupplierId()).getSupplierName() : "");

                            // 查询货主信息
                            WarehousingEntry entry = warehousingEntryService.getById(detail.getWarehousingEntryId());
                            if (entry != null) {
                                String ownerName = getConsignorNameById(entry.getConsignorId());
                                record.put("ownerName", ownerName != null ? ownerName : "");
                            } else {
                                record.put("ownerName", "");
                            }
                        } else {
                            record.put("supplierName", "");
                            record.put("ownerName", "");
                        }
                    } else {
                        // SKU未找到时使用明细表中的数据
                        record.put("goodsCode", "");
                        record.put("goodsName", "");
                        record.put("skuCode", "");
                        record.put("skuName", "");
                        record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                        record.put("totalWeight", 0.0);
                        record.put("totalVolume", 0.0);
                        record.put("supplierName", "");

                        // 查询货主信息
                        WarehousingEntry entry = warehousingEntryService.getById(detail.getWarehousingEntryId());
                        if (entry != null) {
                            String ownerName = getConsignorNameById(entry.getConsignorId());
                            record.put("ownerName", ownerName != null ? ownerName : "");
                        } else {
                            record.put("ownerName", "");
                        }
                    }
                } catch (Exception e) {
                    // 异常时使用默认值
                    record.put("goodsCode", "");
                    record.put("goodsName", "");
                    record.put("skuCode", "");
                    record.put("skuName", "");
                    record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                    record.put("totalWeight", 0.0);
                    record.put("totalVolume", 0.0);
                    record.put("supplierName", "");
                    record.put("ownerName", "");
                }
            } else {
                // 没有SKU ID时使用默认值
                record.put("goodsCode", "");
                record.put("goodsName", "");
                record.put("skuCode", "");
                record.put("skuName", "");
                record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                record.put("totalWeight", 0.0);
                record.put("totalVolume", 0.0);
                record.put("supplierName", "");

                // 查询货主信息
                WarehousingEntry entry = warehousingEntryService.getById(detail.getWarehousingEntryId());
                if (entry != null) {
                    String ownerName = getConsignorNameById(entry.getConsignorId());
                    record.put("ownerName", ownerName != null ? ownerName : "");
                } else {
                    record.put("ownerName", "");
                }
            }

            dataList.add(record);
        }

        PageResult pageResult = new PageResult();
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setData(dataList);
        pageResult.setPages((int) resultPage.getPages());
        pageResult.setCurrentPage(current);
        Result result = Result.success();
        result.setData(pageResult);
        return result;
    }


    /**
     * 确认卸货
     *
     * @param data 确认参数
     * @return 操作结果
     */
    @PostMapping("/toBeUnloaded/confirm")
    public Result confirmUnloaded(@RequestBody ConfirmUnloadedRequest data) {
        try {
            LocalDateTime unloadTime = null;
            if (data.getUnloadTime() != null) {
                // 解析日期时间字符串
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                unloadTime = LocalDateTime.parse(data.getUnloadTime(), formatter);
            }

            warehousingEntryService.confirmUnloaded(data.getIds(), data.getUnloadStaffId(), unloadTime);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 撤销卸货状态
     *
     * @param ids 待撤销的记录ID列表
     * @return 操作结果
     */
    @PostMapping("/toBeUnloaded/revert")
    public Result revertUnloaded(@RequestBody List<Long> ids) {
        try {
            warehousingEntryService.revertUnloaded(ids);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    // ==================== 待分拣接口 ====================

    // ... existing code ...
    /**
     * 分页查询待分拣列表
     *
     * @param current      当前页码
     * @param size         每页条数
     * @param supplierName 供应商名称（模糊查询）
     * @param skuCode      规格编码（模糊查询）
     * @return 分页数据
     */
    @GetMapping("/toBeSorted/page")
    public Result queryToBeSortedPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String skuCode) {
        // 实现分页查询逻辑
        Page<WarehousingEntryDetails> page = new Page<>(current, size);

        // 构造查询条件
        LambdaQueryWrapper<WarehousingEntryDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarehousingEntryDetails::getIsDel, 1); // 未删除的记录
        queryWrapper.eq(WarehousingEntryDetails::getStatus, 3); // 状态为已卸货

        // 执行分页查询
        Page<WarehousingEntryDetails> resultPage = warehousingEntryDetailsMapper.selectPage(page, queryWrapper);

        // 转换数据格式以匹配前端需要的字段
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (WarehousingEntryDetails detail : resultPage.getRecords()) {
            Map<String, Object> record = new HashMap<>();
            record.put("id", detail.getId());

            // 根据skuId查询商品信息
            if (detail.getSkuId() != null && detail.getSkuId() > 0) {
                try {
                    ItemSku sku = itemSkuMapper.getById(detail.getSkuId());
                    if (sku != null) {
                        record.put("goodsCode", sku.getCode() != null ? sku.getCode() : "");
                        record.put("goodsName", sku.getTitle() != null ? sku.getTitle() : "");
                        record.put("skuCode", sku.getCode() != null ? sku.getCode() : "");
                        record.put("skuName", sku.getTitle() != null ? sku.getTitle() : "");
                        record.put("price", sku.getPrice() != null ? sku.getPrice().doubleValue() :
                                (detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0));

                        // 计算总重量和总体积
                        int count = detail.getCount() != null ? detail.getCount() : 0;
                        if (sku.getProductWeight() != null) {
                            record.put("totalWeight", sku.getProductWeight().doubleValue() * count / 1000); // 转换为kg
                        } else {
                            record.put("totalWeight", 0.0);
                        }

                        if (sku.getProductVolume() != null) {
                            record.put("totalVolume", sku.getProductVolume().doubleValue() * count / 1000000); // 转换为立方米
                        } else {
                            record.put("totalVolume", 0.0);
                        }

                        // 根据spuId查询SPU信息获取供应商
                        ItemSpu spu = itemSpuMapper.getById(sku.getSpuId());
                        if (spu != null) {
                            record.put("supplierId", spu.getSupplierId());
                            record.put("supplierName", supplierMapper.getById(spu.getSupplierId()));
                        } else {
                            // 如果SPU查询不到，则尝试通过detail中的supplierId查询
                            if (detail.getSupplierId() != null ) {
                                Supplier supplier = supplierMapper.getById(Math.toIntExact(detail.getSupplierId()));
                                if (supplier != null) {
                                    record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                                } else {
                                    record.put("supplierName", "");
                                }
                            } else {
                                record.put("supplierName", "");
                            }
                        }
                    } else {
                        // SKU未找到时使用默认值
                        record.put("goodsCode", "");
                        record.put("goodsName", "");
                        record.put("skuCode", "");
                        record.put("skuName", "");
                        record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                        record.put("totalWeight", 0.0);
                        record.put("totalVolume", 0.0);

                        // 通过detail中的supplierId查询供应商名称
                        if (detail.getSupplierId() != null && detail.getSupplierId() > 0) {
                            Supplier supplier = supplierMapper.getById(Math.toIntExact(detail.getSupplierId()));
                            if (supplier != null) {
                                record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                            } else {
                                record.put("supplierName", "");
                            }
                        } else {
                            record.put("supplierName", "");
                        }
                    }
                } catch (Exception e) {
                    // 异常时使用默认值
                    record.put("goodsCode", "");
                    record.put("goodsName", "");
                    record.put("skuCode", "");
                    record.put("skuName", "");
                    record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                    record.put("totalWeight", 0.0);
                    record.put("totalVolume", 0.0);

                    // 通过detail中的supplierId查询供应商名称
                    if (detail.getSupplierId() != null && detail.getSupplierId() > 0) {
                        Supplier supplier = supplierMapper.getById(Math.toIntExact(detail.getSupplierId()));
                        if (supplier != null) {
                            record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                        } else {
                            record.put("supplierName", "");
                        }
                    } else {
                        record.put("supplierName", "");
                    }
                }
            } else {
                // 没有SKU ID时使用默认值
                record.put("goodsCode", "");
                record.put("goodsName", "");
                record.put("skuCode", "");
                record.put("skuName", "");
                record.put("price", detail.getPrice() != null ? detail.getPrice().doubleValue() : 0.0);
                record.put("totalWeight", 0.0);
                record.put("totalVolume", 0.0);

                // 通过detail中的supplierId查询供应商名称
                if (detail.getSupplierId() != null && detail.getSupplierId() > 0) {
                    Supplier supplier = supplierMapper.getById(Math.toIntExact(detail.getSupplierId()));
                    if (supplier != null) {
                        record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                    } else {
                        record.put("supplierName", "");
                    }
                } else {
                    record.put("supplierName", "");
                }
            }

            // 查询货主信息
            WarehousingEntry entry = warehousingEntryService.getById(detail.getWarehousingEntryId());
            if (entry != null) {
                String ownerName = getConsignorNameById(entry.getConsignorId());
                record.put("ownerName", ownerName != null ? ownerName : "");
            } else {
                record.put("ownerName", "");
            }

            // 设置分拣量，默认为0
            record.put("sortQuantity", 0);

            dataList.add(record);
        }

        PageResult pageResult = new PageResult();
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setData(dataList);
        pageResult.setPages((int) resultPage.getPages());
        pageResult.setCurrentPage(current);
        Result result = Result.success();
        result.setData(pageResult);
        return result;
    }



    /**
     * 执行分拣
     *
     * @param data 分拣参数
     * @return 操作结果
     */
    @PostMapping("/toBeSorted/sort")
    public Result performSorting(@RequestBody PerformSortingRequest data) {
        try {
            LocalDateTime expireDate = null;
            if (data.getExpireDate() != null && !data.getExpireDate().isEmpty()) {
                // 解析日期字符串
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                expireDate = LocalDate.parse(data.getExpireDate(), formatter).atStartOfDay();
            }

            warehousingEntryService.performSorting(data.getId(), data.getSortQuantity(), expireDate);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询分拣记录详情
     *
     * @param id 记录ID
     * @return 分拣记录详情
     */
    @GetMapping("/toBeSorted/records/{id}")
    public Result querySortingRecords(@PathVariable Long id) {
        try {
            // 查询分拣记录详情
            LambdaQueryWrapper<WarehousingEntryDetailsSort> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WarehousingEntryDetailsSort::getWarehousingEntryDetailsId, id);
            queryWrapper.eq(WarehousingEntryDetailsSort::getIsDel, 1);
            List<WarehousingEntryDetailsSort> sortRecords = warehousingEntryDetailsSortMapper.selectList(queryWrapper);

            return Result.success(sortRecords);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 确认分拣完成
     *
     * @param ids 待确认的记录ID列表
     * @return 操作结果
     */
    @PostMapping("/toBeSorted/confirm")
    public Result confirmSortingCompleted(@RequestBody List<Long> ids) {
        try {
            warehousingEntryService.confirmSortingCompleted(ids);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 撤销分拣状态
     *
     * @param ids 待撤销的记录ID列表
     * @return 操作结果
     */
    @PostMapping("/toBeSorted/revert")
    public Result revertSorting(@RequestBody List<Long> ids) {
        try {
            warehousingEntryService.revertSorting(ids);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除分拣记录
     *
     * @param id 分拣记录ID
     * @return 操作结果
     */
    @DeleteMapping("/toBeSorted/record/{id}")
    public Result deleteSortingRecord(@PathVariable Long id) {
        try {
            // 逻辑删除分拣记录
            WarehousingEntryDetailsSort sortRecord = new WarehousingEntryDetailsSort();
            sortRecord.setId(id);
            sortRecord.setIsDel(2); // 已删除
            sortRecord.setUpdateTime(LocalDateTime.now());
            warehousingEntryDetailsSortMapper.updateById(sortRecord);

            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    // ==================== 待上架接口 ====================

    /**
     * 分页查询待上架列表
     *
     * @param current      当前页码
     * @param size         每页条数
     * @param supplierName 供应商名称（模糊查询）
     * @param skuCode      规格编码（模糊查询）
     * @return 分页数据
     */
    @GetMapping("/toBeOnTheShelves/page")
    public Result queryToBeOnTheShelvesPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String skuCode) {
        try {
            // 实现分页查询逻辑
            Page<WarehousingEntryDetailsSort> page = new Page<>(current, size);

            // 构造查询条件
            LambdaQueryWrapper<WarehousingEntryDetailsSort> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WarehousingEntryDetailsSort::getIsDel, 1); // 未删除的记录
            queryWrapper.eq(WarehousingEntryDetailsSort::getStatus, 2); // 状态为已完成分拣

            // 执行分页查询
            Page<WarehousingEntryDetailsSort> resultPage = warehousingEntryDetailsSortMapper.selectPage(page, queryWrapper);

            // 转换数据格式以匹配前端需要的字段
            List<Map<String, Object>> dataList = new ArrayList<>();
            for (WarehousingEntryDetailsSort sortRecord : resultPage.getRecords()) {
                Map<String, Object> record = new HashMap<>();
                record.put("id", sortRecord.getId());

                // 初始化默认值
                record.put("goodsCode", "未知编码");
                record.put("goodsName", "未知商品");
                record.put("skuCode", "未知规格编码");
                record.put("skuName", "未知规格");
                record.put("price", 0.0);
                record.put("totalVolume", 0.0);
                record.put("supplierName", "未知供应商");
                record.put("ownerName", "未知货主");

                // 根据skuId查询商品信息
                if (sortRecord.getSkuId() != null && sortRecord.getSkuId() > 0) {
                    try {
                        // 使用现有的getById方法查询
                        ItemSku sku = itemSkuMapper.getById(sortRecord.getSkuId());
                        if (sku != null) {
                            record.put("goodsCode", sku.getCode() != null ? sku.getCode() : "未知编码");
                            record.put("goodsName", sku.getTitle() != null ? sku.getTitle() : "未知商品");
                            record.put("skuCode", sku.getCode() != null ? sku.getCode() : "未知规格编码");
                            record.put("skuName", sku.getTitle() != null ? sku.getTitle() : "未知规格");
                            record.put("price", sku.getPrice() != null ? sku.getPrice().doubleValue() : 0.0);

                            // 计算总体积
                            int count = sortRecord.getCount() != null ? sortRecord.getCount() : 0;
                            if (sku.getProductVolume() != null) {
                                record.put("totalVolume", sku.getProductVolume().doubleValue() * count / 1000000); // 转换为立方米
                            } else {
                                record.put("totalVolume", 0.0);
                            }

                            // 根据spuId查询SPU信息获取供应商
                            if (sku.getSpuId() != null && sku.getSpuId() > 0) {
                                ItemSpu spu = itemSpuMapper.getById(sku.getSpuId());
                                if (spu != null) {
                                    // 如果SPU中有供应商ID，则通过ID查询供应商名称
                                    if (spu.getSupplierId() != null && spu.getSupplierId() > 0) {
                                        Supplier supplier = supplierMapper.getById(spu.getSupplierId());
                                        String ownerName = getConsignorNameById(spu.getConsignorId());
                                        record.put("ownerName", ownerName != null && !ownerName.isEmpty() ? ownerName : "未知货主");
                                        if (supplier != null) {
                                            record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "未知供应商");
                                        } else {
                                            record.put("supplierName", "未知供应商");
                                        }
                                    } else {
                                        record.put("supplierName", "未知供应商");
                                    }
                                } else {
                                    record.put("supplierName", "未知供应商");
                                }
                            } else {
                                record.put("supplierName", "未知供应商");
                            }
                        }
                    } catch (Exception e) {
                        // 发生异常时保持默认值
                        System.err.println("查询SKU信息时发生异常: " + e.getMessage());
                        e.printStackTrace();
                    }
                }

                // 查询货主信息
                try {
                    WarehousingEntryDetails detail = warehousingEntryDetailsMapper.selectById(sortRecord.getWarehousingEntryDetailsId());
                    if (detail != null) {
                        WarehousingEntry entry = warehousingEntryService.getById(detail.getWarehousingEntryId());
                        if (entry != null) {
                            String ownerName = getConsignorNameById(entry.getConsignorId());
                            record.put("ownerName", ownerName != null && !ownerName.isEmpty() ? ownerName : "未知货主");
                        }
                    }
                } catch (Exception e) {
                    // 发生异常时保持默认值
                    System.err.println("查询货主信息时发生异常: " + e.getMessage());
                    e.printStackTrace();
                }

                // 设置分拣数量和上架数量
                record.put("sortQuantity", sortRecord.getCount() != null ? sortRecord.getCount() : 0);
                record.put("shelvedQuantity", 0); // 默认为0，表示尚未上架

                dataList.add(record);
            }

            PageResult pageResult = new PageResult();
            pageResult.setTotal(resultPage.getTotal());
            pageResult.setData(dataList);
            pageResult.setPages((int) resultPage.getPages());
            pageResult.setCurrentPage(current);
            Result result = Result.success();
            result.setData(pageResult);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询待上架列表失败：" + e.getMessage());
        }
    }
    /**
     * 执行上架
     *
     * @param data 上架参数
     * @return 操作结果
     */
    @PostMapping("/toBeOnTheShelves/shelve")
    public Result performShelving(@RequestBody PerformShelvingRequest data) {
        try {
            warehousingEntryService.performShelving(data.getItems(), data.getLocationIds());
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 撤销上架状态
     *
     * @param ids 待撤销的记录ID列表
     * @return 操作结果
     */
    @PostMapping("/toBeOnTheShelves/revert")
    public Result revertShelved(@RequestBody List<Long> ids) {
        try {
            warehousingEntryService.revertShelved(ids);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询库位列表
     *
     * @param current       当前页码
     * @param size          每页条数
     * @param warehouseName 仓库名称（模糊查询）
     * @param areaName      库区名称（模糊查询）
     * @return 分页数据
     */
    @GetMapping("/location/page")
    public Result queryLocationPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String warehouseName,
            @RequestParam(required = false) String areaName) {
        try {
            // 创建分页对象
            Page<WarehouseAreaLoca> page = new Page<>(current, size);

            // 构造查询条件
            LambdaQueryWrapper<WarehouseAreaLoca> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WarehouseAreaLoca::getIsDel, 1); // 未删除的记录

            // 如果提供了仓库名称或库区名称，则添加查询条件
            if (warehouseName != null && !warehouseName.isEmpty()) {
                // 需要关联查询仓库表
            }

            if (areaName != null && !areaName.isEmpty()) {
                // 需要关联查询库区表
            }

            // 执行分页查询
            Page<WarehouseAreaLoca> resultPage = warehouseAreaLocaMapper.selectPage(page, queryWrapper);

            // 转换为VO对象
            List<LocationVO> locationList = resultPage.getRecords().stream().map(loca -> {
                LocationVO location = new LocationVO();
                location.setId(Long.valueOf(loca.getId()));
                location.setLocaCode(loca.getLocaCode());
                location.setLocaLen(loca.getLocaLen() != null ? loca.getLocaLen().doubleValue() : 0.0);
                location.setLocaWidth(loca.getLocaWidth() != null ? loca.getLocaWidth().doubleValue() : 0.0);
                location.setLocaHeight(loca.getLocaHeight() != null ? loca.getLocaHeight().doubleValue() : 0.0);
                location.setLocalVolume(loca.getLocalVolume() != null ? loca.getLocalVolume().doubleValue() : 0.0);
                location.setLocalBearingCapacity(loca.getLocalBearingCapacity() != null ? loca.getLocalBearingCapacity().doubleValue() : 0.0);
                location.setTunnelNumber(loca.getTunnelNumber());
                location.setShelfNumber(loca.getShelfNumber());
                location.setLayerNumber(loca.getLayerNumber());
                location.setLocalId(loca.getLocalId());
                location.setIsDel(loca.getIsDel());
                return location;
            }).collect(Collectors.toList());

            PageResult pageResult = new PageResult();
            pageResult.setTotal(resultPage.getTotal());
            pageResult.setData(locationList);
            pageResult.setPages((int) resultPage.getPages());
            pageResult.setCurrentPage(current);
            Result result = Result.success();
            result.setData(pageResult);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询库位列表失败：" + e.getMessage());
        }
    }

    // ==================== 收货明细接口 ====================

    /**
     * 分页查询收货明细列表
     *
     * @param current      当前页码
     * @param size         每页条数
     * @param supplierName 供应商名称（模糊查询）
     * @param skuCode      规格编码（模糊查询）
     * @return 分页数据
     */
    @GetMapping("/receiptDetails/page")
    public Result queryReceiptDetailsPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String skuCode) {
        try {
            // 实现分页查询收货明细列表逻辑
            Page<WarehousingEntryUp> page = new Page<>(current, size);

            // 构造查询条件
            LambdaQueryWrapper<WarehousingEntryUp> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WarehousingEntryUp::getIsDel, 1); // 未删除的记录
            queryWrapper.eq(WarehousingEntryUp::getStatus, 2); // 状态为已上架

            // 执行分页查询
            Page<WarehousingEntryUp> resultPage = warehousingEntryUpMapper.selectPage(page, queryWrapper);

            // 转换数据格式以匹配前端需要的字段
            List<Map<String, Object>> dataList = new ArrayList<>();
            for (WarehousingEntryUp upRecord : resultPage.getRecords()) {
                Map<String, Object> record = new HashMap<>();
                record.put("id", upRecord.getId());

                // 根据skuId查询商品信息
                if (upRecord.getSkuId() != null && upRecord.getSkuId() > 0) {
                    try {
                        ItemSku sku = itemSkuMapper.getById(upRecord.getSkuId());
                        if (sku != null) {
                            record.put("goodsCode", sku.getCode() != null ? sku.getCode() : "");
                            record.put("goodsName", sku.getTitle() != null ? sku.getTitle() : "");
                            record.put("skuCode", sku.getCode() != null ? sku.getCode() : "");
                            record.put("skuName", sku.getTitle() != null ? sku.getTitle() : "");
                            record.put("price", sku.getPrice() != null ? sku.getPrice().doubleValue() : 0.0);

                            // 计算总重量和总体积
                            int count = upRecord.getCount() != null ? upRecord.getCount() : 0;
                            if (sku.getProductWeight() != null) {
                                record.put("totalWeight", sku.getProductWeight().doubleValue() * count / 1000); // 转换为kg
                            } else {
                                record.put("totalWeight", 0.0);
                            }

                            if (sku.getProductVolume() != null) {
                                record.put("totalVolume", sku.getProductVolume().doubleValue() * count / 1000000); // 转换为立方米
                            } else {
                                record.put("totalVolume", 0.0);
                            }
                        } else {
                            // SKU未找到时使用默认值
                            record.put("goodsCode", "");
                            record.put("goodsName", "");
                            record.put("skuCode", "");
                            record.put("skuName", "");
                            record.put("price", 0.0);
                            record.put("totalWeight", 0.0);
                            record.put("totalVolume", 0.0);
                        }
                    } catch (Exception e) {
                        // 异常时使用默认值
                        record.put("goodsCode", "");
                        record.put("goodsName", "");
                        record.put("skuCode", "");
                        record.put("skuName", "");
                        record.put("price", 0.0);
                        record.put("totalWeight", 0.0);
                        record.put("totalVolume", 0.0);
                    }
                } else {
                    // 没有SKU ID时使用默认值
                    record.put("goodsCode", "");
                    record.put("goodsName", "");
                    record.put("skuCode", "");
                    record.put("skuName", "");
                    record.put("price", 0.0);
                    record.put("totalWeight", 0.0);
                    record.put("totalVolume", 0.0);
                }

                // 查询货主信息
                try {
                    if (upRecord.getDetailsSortId() != null) {
                        WarehousingEntryDetailsSort sortRecord = warehousingEntryDetailsSortMapper.selectById(upRecord.getDetailsSortId());
                        if (sortRecord != null && sortRecord.getWarehousingEntryDetailsId() != null) {
                            WarehousingEntryDetails detail = warehousingEntryDetailsMapper.selectById(sortRecord.getWarehousingEntryDetailsId());
                            record.put("damageCount",sortRecord.getDamageCount());
                            record.put("surpassCount",sortRecord.getSurpassCount());
                            record.put("lackCount",sortRecord.getLackCount());
                            record.put("count",sortRecord.getCount());
                            if (detail != null) {
                                WarehousingEntry entry = warehousingEntryService.getById(detail.getWarehousingEntryId());
                                if (entry != null) {
                                    String ownerName = getConsignorNameById(entry.getConsignorId());
                                    record.put("ownerName", ownerName != null ? ownerName : "");
                                } else {
                                    record.put("ownerName", "");
                                }
                            } else {
                                record.put("ownerName", "");
                            }
                        } else {
                            record.put("ownerName", "");
                        }
                    } else {
                        record.put("ownerName", "");
                    }
                } catch (Exception e) {
                    record.put("ownerName", "");
                }

                // 查询供应商信息
                try {
                    if (upRecord.getSkuId() != null && upRecord.getSkuId() > 0) {
                        ItemSku sku = itemSkuMapper.getById(upRecord.getSkuId());
                        if (sku != null && sku.getSpuId() != null) {
                            ItemSpu spu = itemSpuMapper.getById(sku.getSpuId());
                            Long consignorId = spu.getConsignorId();
                            record.put("ownerName", getConsignorNameById(consignorId));
                            if (spu != null && spu.getSupplierId() != null) {
                                Supplier supplier = supplierMapper.getById(spu.getSupplierId());
                                if (supplier != null) {
                                    record.put("supplierName", supplier.getSupplierName() != null ? supplier.getSupplierName() : "");
                                } else {
                                    record.put("supplierName", "");
                                }
                            } else {
                                record.put("supplierName", "");
                            }
                        } else {
                            record.put("supplierName", "");
                        }
                    } else {
                        record.put("supplierName", "");
                    }
                } catch (Exception e) {
                    record.put("supplierName", "");
                }

                // 设置上架数量
                record.put("shelvedQuantity", upRecord.getCount() != null ? upRecord.getCount() : 0);

                dataList.add(record);
            }

            PageResult pageResult = new PageResult();
            pageResult.setTotal(resultPage.getTotal());
            pageResult.setData(dataList);
            pageResult.setPages((int) resultPage.getPages());
            pageResult.setCurrentPage(current);
            Result result = Result.success();
            result.setData(pageResult);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询收货明细列表失败：" + e.getMessage());
        }
    }
    // ==================== 公共接口 ====================

    /**
     * 查询员工列表（用于选择卸货员工）
     *
     * @param current 当前页码
     * @param size    每页条数
     * @param username 员工编号（模糊查询）
     * @param name     员工名称（模糊查询）
     * @param role     角色（模糊查询）
     * @return 分页数据
     */
    @GetMapping("/staff/page")
    public Result queryStaffPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String role) {
        try {
            // 创建分页对象
            PageQuery<User> pageQuery = new PageQuery<>();
            pageQuery.setPage(current);
            pageQuery.setPageSize(size);

            // 创建查询条件
            User userQuery = new User();
            if (username != null && !username.isEmpty()) {
                userQuery.setUsername(username);
            }
            if (name != null && !name.isEmpty()) {
                userQuery.setName(name);
            }
            if (role != null && !role.isEmpty()) {
                userQuery.setRole(role);
            }
            pageQuery.setBody(userQuery);

            // 执行分页查询
            List<User> userList = userMapper.list(pageQuery);
            long total = userMapper.count(userQuery);

            // 转换为VO对象
            List<Map<String, Object>> staffList = userList.stream().map(user -> {
                Map<String, Object> staff = new HashMap<>();
                staff.put("id", user.getId());
                staff.put("username", user.getUsername());
                staff.put("name", user.getName());
                staff.put("role", user.getRole() != null ? getRoleName(user.getRole()) : "");
                staff.put("gender", user.getGender() != null ? (user.getGender() == 1 ? "男" : "女") : "");
                staff.put("phone", user.getPhone() != null ? user.getPhone() : "");
                return staff;
            }).collect(Collectors.toList());

            // 构造分页结果
            PageResult pageResult = new PageResult();
            pageResult.setTotal(total);
            pageResult.setData(staffList);
            pageResult.setPages((int) Math.ceil((double) total / size));
            pageResult.setCurrentPage(current);

            Result result = Result.success();
            result.setData(pageResult);
            return result;
        } catch (Exception e) {
            return Result.error("查询员工列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据角色ID获取角色名称
     * @param roleId 角色ID
     * @return 角色名称
     */
    private String getRoleName(Integer roleId) {
        switch (roleId) {
            case 1:
                return "管理员";
            case 2:
                return "操作员";
            case 3:
                return "审核员";
            default:
                return "未知";
        }
    }

    /**
     * 查询货主列表（用于选择货主）
     *
     * @return 货主列表
     */
    @GetMapping("/owner/list")
    public Result queryOwnerList() {
        try {
            // 查询所有未删除的货主
            List<Consignor> consignors = consignorMapper.selectList(null);

            // 转换为VO对象
            List<OwnerVO> ownerList = consignors.stream().map(consignor -> {
                OwnerVO owner = new OwnerVO();
                owner.setId(consignor.getId());
                owner.setName(consignor.getConsignorName());
                return owner;
            }).collect(Collectors.toList());

            return Result.success(ownerList);
        } catch (Exception e) {
            return Result.error("查询货主列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据商品名称和规格编码查询商品列表（用于到货通知添加商品）
     *
     * @param goodsName 商品名称（模糊查询）
     * @param skuCode   规格编码（模糊查询）
     * @return 商品列表
     */
    @GetMapping("/goods/list")
    public Result queryGoodsList(
            @RequestParam(required = false) String goodsName,
            @RequestParam(required = false) String skuCode) {
        try {
            // 创建查询结果列表
            List<GoodsVO> goodsList = new ArrayList<>();

            // 查询所有供应商和品牌，用于后续关联
            List<Supplier> suppliers = supplierMapper.listAll();
            Map<Integer, String> supplierMap = suppliers.stream()
                    .collect(Collectors.toMap(Supplier::getId, Supplier::getSupplierName, (key1, key2) -> key1));

            List<Brand> brands = brandMapper.listAll();
            Map<Integer, String> brandMap = brands.stream()
                    .collect(Collectors.toMap(Brand::getId, Brand::getName, (key1, key2) -> key1));

            // 构建查询条件
            ItemSpuQuery query = new ItemSpuQuery();
            if (goodsName != null) {
                query.setTitle(goodsName);
            }

            PageQuery<ItemSpuQuery> pageQuery = new PageQuery<>();
            pageQuery.setBody(query);
            pageQuery.setPage(1);
            pageQuery.setPageSize(100); // 限制查询数量

            // 查询SPU列表
            List<ItemSpu> spuList = itemSpuMapper.listByPage(pageQuery);

            // 遍历SPU列表，构建返回数据
            for (ItemSpu spu : spuList) {
                // 查询SPU关联的SKU列表
                List<ItemSku> skuList = itemSkuMapper.listBySpuId(spu.getId());

                // 如果提供了规格编码，则过滤SKU
                if (skuCode != null && !skuCode.isEmpty()) {
                    skuList = skuList.stream()
                            .filter(sku -> sku.getCode() != null && sku.getCode().contains(skuCode))
                            .collect(Collectors.toList());
                }

                // 为每个SKU构建返回数据
                for (ItemSku sku : skuList) {
                    GoodsVO goodsVO = new GoodsVO();
                    goodsVO.setId(sku.getId());
                    goodsVO.setGoodsCode(spu.getId().toString());
                    goodsVO.setGoodsName(spu.getTitle());
                    goodsVO.setSkuCode(sku.getCode());
                    goodsVO.setSkuName(sku.getTitle());
                    goodsVO.setSupplierName(supplierMap.getOrDefault(spu.getSupplierId(), ""));
                    goodsVO.setBrand(brandMap.getOrDefault(spu.getBrandId(), ""));
                    goodsVO.setUnit(sku.getUnit());
                    goodsVO.setPrice(sku.getPrice());
                    goodsList.add(goodsVO);
                }
            }

            return Result.success(goodsList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询商品列表失败：" + e.getMessage());
        }
    }
    // 请求DTO类
    @Data
    static class ConfirmArrivalRequest {
        private List<Long> ids;
        private LocalDate arrivalTime;
    }

    @Data
    static class ConfirmUnloadedRequest {
        private List<Long> ids;
        private Integer unloadStaffId;
        private String unloadTime;
    }

    @Data
    static class PerformSortingRequest {
        private Long id;
        private Integer sortQuantity;
        private String expireDate;
    }

    @Data
    static class PerformShelvingRequest {
        private List<ShelvingItem> items;
        private List<Long> locationIds;
    }

    @Data
    public static class ShelvingItem {
        private Long id;
        private Integer quantity;
    }

    @Data
    static class StaffQueryDTO {
        private String username;
        private String name;
        private String role;
    }

    // VO类
    @Data
    static class LocationVO {
        private Long id;
        private String warehouseName;
        private String areaName;
        private String category;
        private String locaCode;
        private Double locaLen;
        private Double locaWidth;
        private Double locaHeight;
        private Double localVolume;
        private Double localBearingCapacity;
        private String tunnelNumber;
        private String shelfNumber;
        private String layerNumber;
        private String localId;
        private Integer isDel;
    }

    @Data
    static class StaffVO {
        private Long id;
        private String userCode;
        private String userName;
        private String roleName;
    }

    @Data
    static class OwnerVO {
        private Long id;
        private String name;
    }

    @Data
    static class GoodsVO {
        private Long id;
        private String goodsCode;
        private String goodsName;
        private String skuCode;
        private String skuName;
        private String supplierName;
        private String brand;
        private String unit;
        private BigDecimal price;
    }
}
